package com.xinqi.common.rocketmq.config;

import com.xinqi.common.rocketmq.config.properties.RocketMqProperties;
import com.xinqi.common.rocketmq.dto.RocketMqBean;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.SessionCredentialsProvider;
import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.time.Duration;

/**
 * RocketMq配置
 *
 * @author dzy
 */
@AutoConfiguration
@EnableConfigurationProperties(RocketMqProperties.class)
public class RocketMqConfiguration {

    @Bean
    public RocketMqBean rocketMqBean(RocketMqProperties rocketMqProperties) {
        RocketMqBean bean = new RocketMqBean();
        bean.setKey(rocketMqProperties.getKey());
        bean.setScreet(rocketMqProperties.getScreet());
        bean.setEndpoints(rocketMqProperties.getEndpoints());
        bean.setTopic(rocketMqProperties.getTopic());
        bean.setExamTopic(rocketMqProperties.getExamTopic());
        bean.setDelayTopic(rocketMqProperties.getDelayTopic());
        bean.setUsername(rocketMqProperties.getUsername());
        bean.setPassword(rocketMqProperties.getPassword());
        return bean;
    }

    @Bean
    public Producer defaultProducer(RocketMqBean rocketMqBean) throws ClientException {
        final ClientServiceProvider provider = ClientServiceProvider.loadService();
        // Credential provider is optional for client configuration.
        // This parameter is necessary only when the server ACL is enabled. Otherwise,
        // it does not need to be set by default.
        SessionCredentialsProvider sessionCredentialsProvider =
            new StaticSessionCredentialsProvider(rocketMqBean.getUsername(), rocketMqBean.getPassword());
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(rocketMqBean.getEndpoints())
            // On some Windows platforms, you may encounter SSL compatibility issues. Try turning off the SSL option in
            // client configuration to solve the problem please if SSL is not essential.
            // .enableSsl(false)
            .setCredentialProvider(sessionCredentialsProvider)
            // 设置10秒延迟
            .setRequestTimeout(Duration.ofSeconds(1))
            .build();
        return provider.newProducerBuilder()
            .setClientConfiguration(clientConfiguration)
            .build();
    }

}
